package com.cn.zaprk;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @PackageName: com.cn.zaprk
 * @ClassName: DBCPUtils
 * @Description:数据库连接池工具类
 * @author: RZS
 * @date: 2022/4/1  20:18
 */
public class DBCPUtils {
    // 定义数据源
    // private static BasicDataSource dataSource;
    private static DataSource dataSource;

    // 初始化数据源
    static {
        // 创建properties工具类
        Properties p = new Properties();
        // 加载配文件流对象
        InputStream ins = DBCPUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");

        try {
            // 加载配置文件
            p.load(ins);

            // 初始化数据源
            dataSource = BasicDataSourceFactory.createDataSource(p);


//            dataSource.setDriverClassName(p.getProperty("driverClassName"));
//            dataSource.setUrl(p.getProperty("url"));
//            dataSource.setUsername(p.getProperty("username"));
//            dataSource.setPassword(p.getProperty("password"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取数据库连接对象
     * @return
     */
    public static Connection getConn() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭资源
     * @param conn
     * @param res
     * @param stat
     */
    public static void close(Connection conn, ResultSet res, Statement... stat){
        try {

            if(res != null){
                res.close();
            }

            for (Statement statement : stat) {
                if(statement != null){
                    statement.close();
                }

            }

            if(conn != null){
                conn.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
